﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using BitwiseOre.SharedMemory.Core.Common;

namespace BitwiseOre.SharedMemory.Core.Primatives
{
    internal sealed class ReadBuffer : IReadBuffer
    {
        private const int EndOfBufferMarker = -1;
        private readonly IBufferLayout _layout;

        private int _current;

        public ReadBuffer(IBufferLayout layout)
        {
            _layout = layout;
        }

        public int ReadByte()
        {
            return IsPastEnd
                       ? EndOfBufferMarker
                       : _layout.Contents[_current++];
        }

        public int ReadArraySegment(ArraySegment<byte> array)
        {
            if (IsPastEnd)
            {
                return 0;
            }

            var count = Math.Min(array.Count, _layout.Length - _current);
            var destination = new ArraySegment<byte>(array.Array, array.Offset, count);

            var result = _layout.Contents.ReadArraySegment(_current, destination);
            _current += result;
            return result;
        }

        public bool IsEmpty
        {
            get { return _layout.Length == 0; }
        }

        public bool IsPastEnd
        {
            get { return _current >= _layout.Length; }
        }

        public void Clear()
        {
            _current = 0;
            _layout.Length = 0;
        }

        public override string ToString()
        {
            return string.Format("Current: {0}, Length: {1}", _current, _layout.Length);
        }
    }
}